package midalgorithms.list;

public class _01AddTwo {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //  真tm不容易啊
        ListNode res = new ListNode();
        ListNode p1 = l1,p2 = l2,p = res;
        int ad = 0;
        while (p1 != null || p2 != null || ad != 0){
            if (p1 == null && p2 == null && ad == 1){
                p.next = new ListNode(1);
                return res.next;
            }
            if (p1 == null){
                if (ad == 0){
                    p.next = p2;
                    return res.next;
                }else {
                    if (p2 != null){
                        p.next = new ListNode((p2.val + ad) % 10);
                        if (p2.val + ad < 10){
                            ad = 0;
                        }
                        p = p.next;
                        p2 = p2.next;
                    }
                }
            }
            if (p2 == null){
                if (ad == 0){
                    p.next = p1;
                    return res.next;
                }else {
                    if (p1 != null){
                        p.next = new ListNode((p1.val + ad) % 10);
                        if (p1.val + ad < 10){
                            ad = 0;
                        }
                        p = p.next;
                        p1 = p1.next;
                    }
                }
            }
            if (p1 != null && p2 != null){
                if (p1.val + p2.val + ad < 10){
                    //没有进位
                    p.next = new ListNode(p1.val + p2.val + ad);
                    p = p.next;
                    p1 = p1.next;
                    p2 = p2.next;
                    ad = 0;
                }else {
                    p.next = new ListNode((p1.val + p2.val + ad) % 10);
                    p = p.next;
                    p1 = p1.next;
                    p2 = p2.next;
                    ad = 1;
                }
            }
        }
        return res.next;
    }
}
